import {Request, Response, NextFunction, Router} from "express";
import {Repository} from "sequelize-typescript";
import {validationResult, body,check} from 'express-validator'
import {Dynamic, Like, Comment} from "../models";
import {checkToken} from "../middlewares/jwt";

interface BodyRequestBody extends Request {
    body: {
        [key: string]: string | undefined
    }
}


const dynamicRouterFactory = (
    dynamicRepository: Repository<Dynamic>,
    likeRepository: Repository<Like>,
    commentRepository: Repository<Comment>,
    ) => Router()
        .get('/all', async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                let category = req.query.category
                let userId = req.query.user_id
                let {page = 1, pageSize = 10} = req.query
                let filter = {}
                let catefilter = {
                    dy_category: 0
                }
                let userIdfilter = {
                    user_id: ''
                }
                if (category) {
                    catefilter.dy_category = Number(category)
                    Object.assign(filter, catefilter)
                }
                if (userId) {
                    userIdfilter.user_id = String(userId)
                    Object.assign(filter, userIdfilter)
                }
                console.log(filter)
                try {
                    let list = await dynamicRepository.findAndCountAll({
                        limit: Number(pageSize),
                        offset: (Number(page) - 1) * Number(pageSize),
                        where: filter,
                        order: [
                            ['createdAt', 'DESC']
                        ],
                        include: [likeRepository, commentRepository]
                    })
                    if (list) {
                        return res.json({
                            code: 1,
                            msg: '动态数据获取成功',
                            list: list.rows,
                            meta: {
                                current_page: page,
                                per_page: pageSize,
                                count: list.count,
                                total: list.count,
                                total_pages: Math.ceil(list.count / Number(pageSize))
                            }
                        })
                    }
                    res.json({
                        errCode: 10001,
                        msg: '动态数据获取失败'
                    })
                } catch (e) {
                    console.log(e);
                    res.json({
                        errCode: 10001,
                        msg: '动态数据获取失败'
                    })
                    next()

                }
            }
        )

        .post('/create', checkToken, [
                body('user_id').isLength({min: 1}),
                body('user_name').isLength({min: 1}),
                body('user_picture').isLength({min: 1}),
                body('dy_content').isLength({min: 1}),
                body('dy_category').isLength({min: 1})
            ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                const error = validationResult(req)
                if (!error.isEmpty()) {
                    return res.status(422).json({
                        errCode: 10000,
                        msg: error.array()
                    })
                }
                try {

                    const list = await dynamicRepository.create({
                        user_id: req.body.user_id,
                        user_name: req.body.user_name,
                        user_picture: req.body.user_picture,
                        dy_content: req.body.dy_content,
                        dy_img: req.body.dy_img,
                        dy_category: req.body.dy_category,
                        created_at: new Date().getTime()
                    })
                    // console.log(list)
                    if (list) {
                        console.log('--- 动态发布成功 ---');
                        return res.json({
                            code: 1,
                            msg: '动态发布成功'
                        })
                    }
                    res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                } catch (e) {
                    console.log(e);
                    res.json({
                        errCode: 10001,
                        msg: '操作失败'
                    })
                    next()
                }
            }
        )
        .post('/del', checkToken, [
            body('id').isLength({min: 1})
        ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
            const error = validationResult(req)
            if (!error.isEmpty()) {
                return res.status(422).json({
                    errCode: 10000,
                    msg: error.array()
                })
            }
            let id = req.body.id
            // console.log(id,typeof id);
            try {
                if (id) {
                    const list = await dynamicRepository.destroy({
                        where: {
                            id: id
                        }
                    })
                    console.log(list)
                    if (list) {
                        console.log('--- 删除操作成功 ---');
                        return res.json({
                            code: 1,
                            msg: '动态删除成功'
                        })
                    }
                }
                return res.json({
                    errCode: 10001,
                    msg: '删除失败'
                })
            } catch (e) {
                console.log(e);
                res.json({
                    errCode: 10001,
                    msg: '操作失败'
                })
                next()
            }
        })
        .get('/detail',[
            check('id').isLength({min: 1})
        ], async (req: BodyRequestBody, res: Response, next: NextFunction) => {
                let dy_id = req.query.id

                try {
                    let data = await dynamicRepository.findOne({
                        where:{
                          id: Number(dy_id)
                        },
                        include: [likeRepository, commentRepository]
                    })
                    if (data) {
                        return res.json({
                            code: 1,
                            msg: '详情获取成功',
                            data: data,
                        })
                    }
                    res.json({
                        errCode: 10001,
                        msg: '动态数据获取失败'
                    })
                } catch (e) {
                    console.log(e);
                    res.json({
                        errCode: 10001,
                        msg: '动态数据获取失败'
                    })
                    next()

                }
            }
        )
    // .get('/', async (req: BodyRequestBody, res: Response, next: NextFunction) => {
    //         const list = await homeRepository.findAll()
    //         res.json(list || {
    //             errCode: 10001,
    //             msg: '数据获取失败'
    //         })
    //     }
    //     // homeRepository.findAll()
    //     // .then(posts => res.json(posts))
    //     // .catch(next)
    // )

    // .get('/', async (req, res, next) => {
    //         const list = await homeRepository.findAll()
    //         res.json(list || {
    //             errCode: 10001,
    //             msg: '数据获取失败'
    //         })
    //     }
    //     // homeRepository.findByPk(req.params.id)
    //     // .then(post => post
    //     //   ? res.json(post)
    //     //   : next({statusCode: 404}))
    //     // .catch(next)
    // )
    //
    // .post('/posts', (req, res, next) =>
    //     homeRepository.create(req.body)
    //         .then(post => res.json(post))
    //         .catch(next)
    // )

;
export default dynamicRouterFactory
